import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

request.interceptors.request.use((config) => {
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

request.interceptors.response.use(
  (res) => {
    const { data, meta } = res.data
    if (meta.status === 400) {
      store.commit('user/logout')
      router.push('/login')
      Message.error('登录过期')
      return Promise.reject(new Error(meta.msg))
    }
    return data
  },
  (err) => {
    Message.error(err.msg)
    return Promise.reject(new Error(err.msg))
  }
)

export default request
